<template>
  <div class="w-full h-full relative">
    <div id="fengmap"></div>
    <div class="route-line">
      <el-tabs v-model="activeName" class="demo-tabs">
        <el-tab-pane label="正常模式" name="first">
          <div class="start-end">
            <div class="input-box">
              <div>
                <div
                  class="front-input"
                  style="border: 2px solid #7ed321"
                ></div>
                <el-input placeholder="请输入起点" v-model="startPoint" />
              </div>
              <div class="divide"></div>
              <div>
                <div
                  class="front-input"
                  style="border: 2px solid #ff4c3f"
                ></div>
                <el-input placeholder="请输入终点" v-model="endPoint" />
              </div>
            </div>
            <img src="../../assets/exchange-img.png" alt="" />
          </div>

          <div class="right_btn">
            <el-button @click="clearAll()">清除路线</el-button>
            <el-button type="primary" @click="naviAndDrawLine()"
              >路线搜索</el-button
            >
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup lang="ts">
import { defineComponent, onBeforeUnmount, onMounted, ref } from "vue";
import fengmap from "fengmap/build/fengmap.map.min.js";
import "fengmap/build/fengmap.plugin.ui.min.js"; //UI控件包
import "fengmap/build/fengmap.analyser.min.js"; //分析器包
import "fengmap/build/fengmap.plugin.navi.min.js"; //导航包
import "fengmap/build/fengmap.effect.min.js"; //特效包
import "fengmap/build/fengmap.plugin.markers.min.js"; //特殊标注包
import "fengmap/build/fengmap.plugin.draw.min.js"; //绘图包
import "fengmap/build/fengmap.plugin.location.min.js"; //位置服务相关功能包
import "fengmap/build/fengmap.plugin.export.min.js"; //打印/出图包
import "fengmap/build/fengmap.plugin.layers.min.js"; //附加图层包
import "fengmap/build/fengmap.plugin.debug.min.js"; //性能监控包
import "fengmap/build/fengmap.plugin.fusion.min.js"; //数据融合信息工具包
import "fengmap/build/fengmap.plugin.loader.min.js"; //FBX动态模型加载器插件包

const activeName = ref("first");
const startPoint = ref("");
const endPoint = ref("");
// 人步行速度 80米/分钟
const walkSpeed = 80;
// 方向对应的图标
const directionImg = {
  左: "left.png",
  左前: "left-front.png",
  左后: "left-back.png",
  右前: "right-front.png",
  右后: "right-back.png",
  右: "right.png",
  前: "front.png",
  终: "end-icon.png",
};
let map = null;
let routeAnalyser = null; // 路径分析对象
const searchAnalyser = ref<any>(); // 搜索分析对象
const floorInfos = ref<any>(); // 楼层信息
const start = ref<any>(null); // 起点
const dest = ref<any>(null); // 终点
const startMarker = ref<any>(null);
const endMarker = ref<any>(null); // 起点终点图标
const lineMarker = ref<any>(null); // 路径线
const domMarker = ref<any>(null); // 设置起点  设置终点弹窗
const clickPoint = ref<any>(null); // 点击地图的点坐标
const mode = fengmap.FMNaviMode.MODULE_SHORTEST; // 最短路径
const priority = fengmap.FMNaviPriority.PRIORITY_LIFTFIRST; // 直梯优先
// const activeInput; // 活跃的输入框id
// const searchResult; // 搜索结果
// const selectedIndex = -1; // 选中的搜索结果下标
window.setStart = setStart;
window.setEnd = setEnd;

function initMap() {
  const options = {
    container: document.getElementById("fengmap"),
    appName: "蜂鸟研发SDK_2_0",
    key: "57c7f309aca507497d028a9c00207cf8",
    mapID: "1514920297309614082",
    themeID: "1580453922356207618",
    level: 1,
  };
  map = new fengmap.FMMap(options);
  map.on("loaded", function () {
    floorInfos.value = map.getFloorInfos();
    // 初始化路径分析类
    routeAnalyser = new fengmap.FMNaviWalkAnalyser(
      { map: map },
      () => {
        console.log('路径分析类创建成功')
      },
      () => {
        alert("路径分析类创建失败");
      },
    );
    // 初始化搜索分析对象
    const searchOption = {
      mapID: options.mapID,
      appName: options.appName,
      key: options.key,
    };
    searchAnalyser.value = new fengmap.FMSearchAnalyser(searchOption);
  });

  // 通过点击地图获取起点和终点
  map.on("click", function (e) {
    if (e.level) {
      const model = e.targets.find(
        (item) => item.type === fengmap.FMType.MODEL,
      );
      if (model) {
        clickPoint.value = {
          level: e.level,
          x: model.x,
          y: model.y,
          name: model.name,
        };
        showDomMarker(clickPoint.value);
      }
    }
  });
}

// 显示选择起点终点的选项卡
function showDomMarker(position) {
  if (domMarker.value) {
    domMarker.value.remove();
    domMarker.value = null;
  }
  domMarker.value = new fengmap.FMDomMarker({
    x: position.x,
    y: position.y,
    domHeight: 80,
    domWidth: 200,
    anchor: fengmap.FMMarkerAnchor.BOTTOM,
    content: `<div style=" display: inline-block; width: 200px; text-align: center;">
        <div style="display: flex;margin-bottom: 10px; border-radius: 6px; background-color: white; text-align: center;">
            <span style="flex: 1; color: white;padding: 10px 16px; line-height: 30px; background-color: #2F65EE; border-bottom-left-radius: 6px; border-top-left-radius:6px; " onclick=setStart()>作为起点</span>
            <span style="flex: 1; padding: 10px 16px; line-height: 30px;" onclick=setEnd()>作为终点</span>
        </div>
        <div style="background-image: url('https://developer.fengmap.com/fmAPI/images/navi/marker.png');display: inline-block; width: 32px; height: 32px;background-size:100%;"></div>
    </div>`,
  });
  const level = position.level;
  const floor = map.getFloor(level);
  domMarker.value.addTo(floor);
}

// 设置起点图标和信息
function setStart() {
  // 清除原来的起点图标
  if (startMarker.value) {
    startMarker.value.remove();
  }
  start.value = { ...clickPoint.value };
  const marker = new fengmap.FMImageMarker({
    url: "https://developer.fengmap.com/fmAPI/images/navi/start.png",
    x: clickPoint.value.x,
    y: clickPoint.value.y,
  });
  const level = clickPoint.value.level;
  const floor = map.getFloor(level);
  marker.addTo(floor);
  startMarker.value = marker;
  // 清除选项卡
  domMarker.value?.remove();
  domMarker.value = null;
  startPoint.value = start.value.name || "地图选点";
}

// 设置终点图标和信息
function setEnd() {
  // 清除原来的终点图标
  if (endMarker.value) endMarker.value.remove();
  dest.value = { ...clickPoint.value };
  const marker = new fengmap.FMImageMarker({
    url: "https://developer.fengmap.com/fmAPI/images/navi/end.png",
    x: clickPoint.value.x,
    y: clickPoint.value.y,
  });
  const level = clickPoint.value.level;
  const floor = map.getFloor(level);
  marker.addTo(floor);
  endMarker.value = marker;
  // 清除选项卡
  domMarker.value?.remove();
  domMarker.value = null;

  endPoint.value = dest.value.name || "地图选点";
}

// 分析路径，绘制路线
function naviAndDrawLine() {
  if (!start.value || !dest.value) return;
  if (lineMarker.value) lineMarker.value.remove();

  const request = { start: start.value, dest: dest.value, mode: mode, priority };
  routeAnalyser.route(request, function (result) {

    const segments = [];
    const subs = result.subs;
    let segment = new fengmap.FMSegment();
    for (let index = 0; index < subs.length; index++) {
      const leg = subs[index];
      if (leg.levels[0] === leg.levels[1]) {
        leg.waypoint.points.forEach((point) => {
          point.z = 0.5;
        });
        if (segment.points) {
          let points = [];
          points.push(...leg.waypoint.points);
          points.splice(0, 1);
          segment.points = segment.points.concat(points);
        } else {
          segment.points = leg.waypoint.points;
        }
        segment.level = leg.levels[0];
        if (index == subs.length - 1) {
          segments.push(segment);
        }
      } else {
        segments.push(segment);
        segment = new fengmap.FMSegment();
      }
    }

    const line = new fengmap.FMLineMarker({
      segments: segments,
      smooth: true,
    });
    line.addTo(map);
    lineMarker.value = line;
  });
}

// 清除地图所有元素
function clearAll() {
  startPoint.value = "";
  endPoint.value = "";
  start.value = null;
  dest.value = null;
  if (startMarker.value) {
    startMarker.value.remove();
    startMarker.value = null;
  }
  if (endMarker.value) {
    endMarker.value.remove();
    endMarker.value = null;
  }
  if (lineMarker.value) {
    lineMarker.value.remove();
    lineMarker.value = null;
  }
  if (domMarker.value) {
    domMarker.value.remove();
    domMarker.value = null;
  }
}

onMounted(() => {
  initMap();
});

onBeforeUnmount(() => {
  if (map.value) map.value?.dispose();
});

defineComponent({ name: "FengMapIndex" });
</script>

<style lang="scss">
.route-line {
  @apply absolute top-68px right-10px w-448px px-14px rounded-[8px] bg-[#fff];

  .start-end {
    @apply flex justify-between items-center bg-[#f5f5f5] rounded-6px p-14px;

    .input-box {
      @apply w-[95%];

      .el-input {
        @apply w-[90%] bg-[#f5f5f5];
        border: none !important;
        line-height: 20px;
        font-size: 14px;
      }

      .el-input__wrapper {
        box-shadow: none !important;
        background-color: #f5f5f5 !important;
      }

      input {
        @apply bg-[#f5f5f5];
      }

      .front-input {
        @apply w-10px h-10px;
      }
    }

    img {
      @apply w-14px h-14px cursor-pointer;
    }
  }
}
</style>
